import { LoginFormData, Token, LoginResponse } from '@/types/data'
import { clearToken } from '@/utils/auth'
import request from '@/utils/request'
import { AppThunk } from '../index'
import { changeToken } from '../modules/login'
// 3. 异步action
export function loginAction(formData: LoginFormData): AppThunk {
  return async (dispatch, getState) => {
    // 1. 发请求获取token
    // 写法1：说明❓：request.post<指定的是后台返回data类型> 
    // const res = await request.post<Token>('/authorizations', formData)
    // 写法2：res:类型注解
    const res: LoginResponse = await request.post('/authorizations', formData)
    console.log('token:', res.data)
    // 2. 把token存储到redux
    dispatch(changeToken(res.data))
  }
}

export const logoutAction = (): AppThunk => {
  return async dispatch => {
    dispatch(changeToken({
      token: '',
      refresh_token: ''
    }))
    clearToken()
  }
}